package example.config.tablestore;

import com.alicloud.openservices.tablestore.AsyncClient;
import com.alicloud.openservices.tablestore.ClientConfiguration;
import com.alicloud.openservices.tablestore.SyncClient;
import com.alicloud.openservices.tablestore.model.AlwaysRetryStrategy;
import com.alicloud.openservices.tablestore.model.RetryStrategy;
import example.core.proerties.FcProerties;
import example.core.proerties.YmlUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ObjectUtils;

/**
 * 阿里表格储存 配置类
 * @author 王振宇
 */
@Configuration
public class TableStoreConfiguration {

    /**
     * 读取配置文件。
     */
    FcProerties fcProerties = YmlUtil.getProerties();

    /**
     * 表格储存 重试策略。
     */
    @Autowired(required = false)
    RetryStrategy retryStrategy;

    /**
     * 获取同步客户端。
     * @return 客户端
     */
    @Bean
    public SyncClient syncClient() {
        return new SyncClient(fcProerties.getTableStoreProerties().getEndPoint(),
                fcProerties.getTableStoreProerties().getAccessKeyId(),
                fcProerties.getTableStoreProerties().getAccessKeySecret(),
                fcProerties.getTableStoreProerties().getInstanceName(),
                clientConfiguration());
    }

    /**
     * 获取异步客户端。
     * @return 客户端
     */
    @Bean
    public AsyncClient asyncClient() {
        return new AsyncClient(fcProerties.getTableStoreProerties().getEndPoint(),
                fcProerties.getTableStoreProerties().getAccessKeyId(),
                fcProerties.getTableStoreProerties().getAccessKeySecret(),
                fcProerties.getTableStoreProerties().getInstanceName(),
                clientConfiguration());
    }

    /**
     * 设置表格储存链接属性。
     * @return 配置对象
     */
    private ClientConfiguration clientConfiguration() {
        // ClientConfiguration提供了很多配置项，以下只列举部分。
        ClientConfiguration clientConfiguration = new ClientConfiguration();
        // 设置建立连接的超时时间。单位为毫秒。
        clientConfiguration.setConnectionTimeoutInMillisecond(fcProerties.getTableStoreProerties().getConnectionTimeoutInMillisecond());
        // 设置socket超时时间。单位为毫秒。
        clientConfiguration.setSocketTimeoutInMillisecond(fcProerties.getTableStoreProerties().getSocketTimeoutInMillisecond());
        // 设置重试策略。如果不设置，则采用默认的重试策略。
        if (ObjectUtils.isEmpty(retryStrategy)) {
            // 注入默认策略
            clientConfiguration.setRetryStrategy(new AlwaysRetryStrategy());
        } else {
            clientConfiguration.setRetryStrategy(retryStrategy);
        }
        return clientConfiguration;
    }
}
